package com.mystudy.gmall.controller;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Author: Felix
 * Desc:  该Controller用于接收模拟生成的日志
 */
//标识为controller组件，交给Sprint容器管理，并接收处理请求  如果返回String，会当作网页进行跳转
//@Controller
// @RestController = @Controller + @ResponseBody  会将返回结果转换为json进行响应
@RestController
@Slf4j
public class LoggerController {

    //注入Spring提供的Kafka编程模板
    @Autowired
    KafkaTemplate kafkaTemplate;
    private Logger logger = LoggerFactory.getLogger(LoggerController.class);

    //通过requestMapping匹配请求并交给方法处理
    @RequestMapping("/applog")
    //在模拟数据生成的代码中，我们将数据封装为json，通过post传递给该Controller处理，所以我们通过@RequestBody接收
    public String applog(@RequestBody String jsonLog){
        //将日志落盘
        log.info(jsonLog);
        //logger.trace(jsonLog);
        System.out.println(jsonLog);
        //将不同类型日志发送到kafka主题中
        JSONObject jsonObject = JSON.parseObject(jsonLog);
        if(jsonObject.containsKey("start")){
            //启动日志
            kafkaTemplate.send("gmall_start_bak",jsonLog);
        }else{
            //事件日志
            kafkaTemplate.send("gmall_event_bak",jsonLog);
        }
        return "success";
    }
}

